package com.woniuxy.portal.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.woniuxy.portal.common.enumeration.OrderStatus;
import com.woniuxy.portal.config.AlipayConfig;
import com.woniuxy.portal.model.dto.PayRequest;
import com.woniuxy.portal.model.vo.OrderVo;
import com.woniuxy.portal.service.OrderService;
import com.woniuxy.portal.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yellow Docter
 * @date 2024-10-28
 * @desc 蜗牛创想：www.woniuxy.com
 */
@RestController
@Slf4j
@Api(tags = "订单模块")
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/createOrder/{addressId}")
    @ApiOperation("创建订单")
    public ResponseEntity<String> createOrder(
            @RequestHeader(name = "Authorization", required = false) String token,
            @PathVariable Integer addressId) {
        //01 拿到用户id
        String userId = jwtUtil.getValue(token, "userId");
        //02 创建订单
        String orderNum = orderService.createOrder(Long.parseLong(userId), addressId);
        return ResponseEntity.ok(orderNum);
    }

    /**
     * 查询订单
     */
    @GetMapping("/loadOrdersByStatus")
    @ApiOperation("查询指定状态的订单")
    public ResponseEntity<List<OrderVo>> loadOrdersByStatus(
            @RequestHeader(name = "Authorization", required = false) String token, Integer status) {
         //从token中获取userId
        String userId = jwtUtil.getValue(token, "userId");
        List<OrderVo> orderVos = orderService.queryOrder(Long.parseLong(userId), status);
        return ResponseEntity.ok(orderVos);

    }

    /**
     * 支付接口
     * @return 返回一个包含表单数据的HTML网页
     */
    @PostMapping("/pay")
    @ApiOperation("支付接口")
    public ResponseEntity<String> pay(@RequestBody PayRequest request) {
        //调用业务层支付
        String form = orderService.pay(Long.valueOf(request.getOrderId()));
        return ResponseEntity.ok(form);
    }

    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 支付宝异步回调接口
     * http://内网穿透地址/order/notify
     */
    @SneakyThrows
    @PostMapping("/notify")
    public void aliPayNotify(HttpServletRequest request) {
        //获取所有请求参数，重新创建一个Map再封装一次数据
        Map<String, String> params = request.getParameterMap().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0]));
        // 验证签名
        String sign = params.get("sign");
        String contentV1 = AlipaySignature.getSignCheckContentV1(params);
        boolean rsa256CheckSignature = AlipaySignature.rsa256CheckContent(contentV1,
                sign, alipayConfig.getAlipayPublicKey(), "UTF-8");

        //表示支付成功
        if (rsa256CheckSignature && "TRADE_SUCCESS".equals(params.get("trade_status"))) {
            // 签名验证成功 并且 支付宝回调的状态是成功状态 TRADE_SUCCESS
            log.info("在{}，买家{}进行订单{}的付款，交易名称{}，付款金额{}", params.get("gmt_payment"), params.get("buyer_id"),
                    params.get("out_trade_no"), params.get("subject"), params.get("total_amount"));

            // 支付成功，修改数据库中该订单的状态，out_trade_no即订单ID
            String outTradeNo = params.get("out_trade_no");
            //更新订单状态为待发货
            orderService.updateOrderStatus(Long.valueOf(outTradeNo), OrderStatus.NO_SEND.getCode());

            log.info("订单{}支付成功，状态修改为待发货", outTradeNo);
        } else {
            log.error("支付宝支付失败");
        }
    }
}
